package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseContorller;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseContorller {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;


    @RequestMapping(value = "/contractList",name = "合同管理列表数据")
    public String contractList(@RequestParam(value = "page",defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize){
        //查询
        ContractExample example = new ContractExample();
        //where company_id=?    andCompanyIdEqualTo
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId()).andStateEqualTo(1);

        //order by
        example.setOrderByClause("create_time desc");
        PageInfo pageInfo = contractService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-contractList";
    }

    @RequestMapping(value = "/list",name = "报运单列表")
    public String list(@RequestParam(value = "page",defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize){
        //查询
        ExportExample example = new ExportExample();
        //where company_id=?    andCompanyIdEqualTo
        ExportExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());

        //order by
        example.setOrderByClause("create_time desc");
        PageInfo pageInfo = exportService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-list";
    }

    @RequestMapping(value = "/toExport",name = "报运单列表")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }
    @RequestMapping(value = "/edit",name = "保存报运单")
    public String edit(Export export){

        if (StringUtils.isEmpty(export.getId())){
            export.setId(UUID.randomUUID().toString());
            export.setCompanyId(getCompanyId());
            export.setCompanyName(getCompanyName());
            export.setState(0);
            export.setCreateTime(new Date());
            export.setCreateBy(getUser().getId());//当前登录人细颗粒控制查询
            export.setCreateDept(getUser().getDeptId());//当前登录人的部门
            exportService.save(export);

        }else {
            exportService.update(export);
        }

        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "编辑报运单页面")
    public String toUpdate(String id){
        //查询报运单
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
        //报运单下货物的数据
        List<ExportProduct> exportProductList =exportProductService.findByExportId(id);
        request.setAttribute("eps",exportProductList);
        return "cargo/export/export-update";
    }


    @RequestMapping(value = "/submit",name = "提交")
    public String submit(String id){
        Export export = exportService.findById(id);
        export.setState(1);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/cancel",name = "取消")
    public String cancel(String id){
        Export export = exportService.findById(id);
        export.setState(0);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/delete",name = "删除")
    public String delete(String id){
        exportService.delete(id);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/exportE",name = "删除")
    public String exportE(String id){
        Export export= exportService.findById(id);
        ExportVo exportVo = new ExportVo();
        BeanUtils.copyProperties(export,exportVo);
        //对比后,需要定义的值为exportId，List<ExportProductVo>
        exportVo.setExportId(id);
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
            //对比后,需要定义的值为eid 、exportProductId
            exportProductVo.setEid(exportVo.getId());
            exportProductVo.setExportProductId(exportProduct.getId());
            //添加
            exportVo.getProducts().add(exportProductVo);
        }
        //post提交
        WebClient.create("http://localhost:9090/ws/export/ep").post(exportVo);
        export.setState(5);
        exportService.update(export);
        /*//从海关项目获取结果
        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/ep/" + id).get(ExportResult.class);

        exportService.updateE(exportResult);*/

        return "redirect:/cargo/export/list.do";
    }

    @Autowired
    private DownloadUtil downloadUtil;
    @RequestMapping(value = "/exportPdf",name = "导出报运单的pdf")
    @ResponseBody
    public void exportPdf(String id) throws Exception{

        //1.读取模板
        String templatePath = session.getServletContext().getRealPath("/make/pdfprint/export.jasper");
        FileInputStream is = new FileInputStream(templatePath);
        //当前报运单
        Export export = exportService.findById(id);
        Map<String, Object> parameters = BeanMapUtils.beanToMap(export);
        //当前报运单下货物数据
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        JRDataSource dataSource = new JRBeanCollectionDataSource(exportProductList);


        //数据填充
        JasperPrint jasperPrint = JasperFillManager.fillReport(is,parameters,dataSource);

        byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);

        //ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byteArrayOutputStream.write(bytes);
        downloadUtil.download(byteArrayOutputStream,response,"报运单.pdf ");

    }













}
